<template>
  <div class="update-avatar">
    <img id="image" :src="img" alt="" />
    <div class="toolbar">
      <span @click="$emit('close')">取消</span>
      <span @click="upImg">完成</span>
    </div>
  </div>
</template>
<script>
import 'cropperjs/dist/cropper.css'
import Cropper from 'cropperjs'
import { updateUserAvatar } from '@/api/user.js'
export default {
  name: 'upImg',
  props: {
    img: {
      type: [String, Object],
      required: true
    }
  },
  data() {
    return {
      cropper: null
    }
  },
  created() {},
  mounted() {
    const image = document.getElementById('image')
    const cropper = new Cropper(image, {
      viewMode: 1,
      dragMode: 'move',
      aspectRatio: 1,
      autoCropArea: 1,
      cropBoxMovable: false,
      cropBoxResizable: false,
      background: false,
      movable: true
    })
    this.cropper = cropper
  },
  computed: {},
  methods: {
    upImg() {
      this.cropper.getCroppedCanvas().toBlob(async blob => {
        this.$toast.loading({
          message: '保存中...',
          forbidClick: true,
          loadingType: 'spinner',
          duration: 0
        })
        try {
          const formData = new FormData()
          formData.append('photo', blob)
          const { data } = await updateUserAvatar(formData)
          // 关闭弹层，更新视图
          this.$emit('close')
          this.$emit('update-avatar', data.data.photo)
          this.$toast('更新成功')
        } catch (err) {
          this.$toast('更新失败')
        }
      })
    }
  }
}
</script>
<style lang="less" scoped>
.update-avatar {
  background: #000;
  width: 100%;
  height: 100%;

  .toolbar {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;

    display: flex;
    justify-content: space-between;

    span {
      width: 90px;
      height: 90px;
      font-size: 20px;
      display: flex;
      justify-content: center;
      align-items: center;
      color: #fff;
    }
  }
  img {
    display: block;
    max-width: 100%;
  }
}
</style>
